package com.example.lib_common.util;

import android.app.Application;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 获取上下文的
 * <p>
 * 通过反射  ActivityThread   获取Application  上下文对象
 */
public class AppGlobals {

    private static Application sApplication;

    public static Application getApplication() {
        if (null == sApplication) {
            //反射获取
            try {
                Class<?> aClass = Class.forName("android.app.ActivityThread");
                //获取里面的currentApplication 方法
                Method currentApplication= aClass.getDeclaredMethod("currentApplication");
                //执行invoke方法
                sApplication= (Application) currentApplication.invoke(null,null);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return sApplication;
    }
}
